package com.atguigu.srb.core.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.atguigu.srb.core.entity.dto.ExcelDictDto;
import com.atguigu.srb.core.mapper.DictMapper;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * @className ExcelDtoDictListner
 * @Author sofia
 * @Date 2021/10/3
 * @Describe
 **/
@Slf4j
@NoArgsConstructor
public class ExcelDtoDictListner extends AnalysisEventListener<ExcelDictDto> {

    private DictMapper dictMapper;
    //每次批量导入的数量
    private static final int BATCH_COUNT = 5;

    //批量导入的数据
    private List<ExcelDictDto> list = new ArrayList<>(BATCH_COUNT);

    //构造一个有参构造函数
    public ExcelDtoDictListner(DictMapper dictMapper){
        this.dictMapper = dictMapper;
    }


    @Override
    public void invoke(ExcelDictDto data, AnalysisContext analysisContext) {
        //将数据先存入数据列表中
        list.add(data);

        //当数据列表中的数据达到可以保存的长度时，开始保存数据
        if (list.size()>=BATCH_COUNT){
            saveData();
            //存储完成以后清理list
            list = new ArrayList<>();
        }
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {
        //对不足BATCH_COUNT数量的数据再进行一次存储
        saveData();
        log.info("数据解析完成！");
    }

    //将数据存储到数据库中去
    private void saveData(){
        log.info("开始批量导入{}条数据。。。。。",list.size());
        dictMapper.insertBatch(list);
        log.info("{}条数据存储成功！");
    }
}
